package com.agileai.crm.common;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.FileUploadHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

abstract public class BaseExcelImportHandler extends FileUploadHandler {
    protected String resourceGroupId = null;
	protected String downloadFileName = null;
	protected String templateFileName = null;
    
    public BaseExcelImportHandler() {
        super();
    }
    
    public ViewRenderer doDownloadTemplateAction(DataParam param){
    	ExcelFileHelper excelFileHelper = new ExcelFileHelper(request, response);    	
    	String templateDir = excelFileHelper.getTemplateDirPath(); 
    	File templateFile = new File(templateDir + "/" + this.templateFileName);;
    	try {
    		FileInputStream inputStream = new FileInputStream(templateFile);
    		excelFileHelper.downloadFile(inputStream, downloadFileName);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new NullRenderer();
    }
    
    public ViewRenderer prepareDisplay(DataParam param) {
    	this.setAttributes(param);
        return new LocalRenderer(getPage());
    }
    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
        String responseText = FAIL;
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");

            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);

            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath(resourceGroupId);

            File tempFile = null;
            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
                if (item.isFormField()){
                	continue;
                }
                name = item.getName();

                String location = resourceRelativePath + "/" + name;
                fileFullPath = filePath.getAbsolutePath() + File.separator + name;
                setAttribute("location",location);

                tempFile = new File(fileFullPath);

                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                item.write(tempFile);
                break;
            }
            
            List<DataParam> dataParams = new ArrayList<DataParam>();
            this.buildParams(tempFile,dataParams);
            //modify by ChenJ
            if(null != dataParams && dataParams.size() > 0){
            	this.importRecords(dataParams);
            	responseText = SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxRenderer(responseText);
    }    
    
    abstract protected void buildParams(File uploadedFile,List<DataParam> params) throws Exception;
    abstract protected void importRecords(List<DataParam> params);
}
